package com.sanxiang.controller;

import com.sanxiang.common.CommonResult;
import com.sanxiang.entity.EnterpriseTable;
import com.sanxiang.entity.UserTable;
import com.sanxiang.mapper.EnterpriseTableMapper;
import com.sanxiang.mapper.UserTableMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/syncMysqlToRedis")
public class SyncController {
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private EnterpriseTableMapper enterpriseTableMapper;

    @Resource
    private UserTableMapper userTableMapper;

    @GetMapping("/EnterpriseTable")
    public CommonResult syncMysqlToRedis() {
        for (UserTable user : userTableMapper.selectList(null)) {
            syncEnterprise(user.getUserId());
        }

        return CommonResult.success(getEnterpriseById(1));
    }

    public void syncEnterprise(Integer userId) {
        HashMap<String, Object> map = new HashMap<>();
        //自定义查询
        map.put("enterprise_legal_person_id", userId);

        List<EnterpriseTable> enterpriseTableAll = enterpriseTableMapper.selectByMap(map);
        if (enterpriseTableAll != null) {
            redisTemplate.opsForList().leftPushAll(Integer.toString(userId), enterpriseTableAll);
        }
    }

    public List getEnterpriseById(Integer userId) {
        return redisTemplate.opsForList().range(Integer.toString(userId), 0, -1);

    }
}
